﻿using System.Net.Sockets;
using System.Text;
using mei_cs.comm;
using static mei_cs.comm.Config;

namespace mei_cs.communication;

public static class Comm
{
    public static readonly string Host = GetConfig<ConnectSection>().Host;
    public static readonly int Port = GetConfig<ConnectSection>().Port;
    public static readonly int AsyncPort = GetConfig<ConnectSection>().AsyncPort;
    public static readonly Encoding MsgEncoding = Encoding.UTF8;

    public const int ReconnectTime = 3; // 连接失败后的重连等待时间

    private static void SendBytes(Socket socket, byte[] message)
    {
        var length = MsgEncoding.GetBytes($"{message.Length:D}");
        var n = MsgEncoding.GetBytes($"{length.Length:D05}");
        socket.Send(n);
        socket.Send(length);
        socket.Send(message);
    }

    public static void SendMsg(Socket socket, string str)
    {
        SendBytes(socket, MsgEncoding.GetBytes(str));
    }

    private static byte[] RecvNByte(Socket socket, int n)
    {
        var buffer = new byte[n];
        socket.Receive(buffer);
        return buffer;
    }

    private static byte[] RecvBytes(Socket socket)
    {
        var n = int.Parse(MsgEncoding.GetString(RecvNByte(socket, 5)));
        var length = int.Parse(MsgEncoding.GetString(RecvNByte(socket, n)));
        return RecvNByte(socket, length);
    }

    public static string RecvMsg(Socket socket)
    {
        return MsgEncoding.GetString(RecvBytes(socket));
    }
}